import { useRef, useState, useEffect } from 'react'
import {
  Card,
  Breadcrumb,
  Form,
  Input,
  Button,
  Space,
  Radio,
  Upload,
  message,
  Modal
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Channel } from '@/components/Channel'
import { useDispatch } from 'react-redux'
import {
  publishArticle,
  getArticleInfo,
  editArticle
} from '@/store/actionCreators/article'
import { Link } from 'react-router-dom'
import styles from './index.module.scss'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { useNavigate, useParams } from 'react-router-dom'

const Publish = () => {
  const formRef = useRef(null)
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const params = useParams()

  const [coverType, setCoverType] = useState(1) // 图片类型0-无图，1-1张，3-3张 默认单图
  const [fileList, setFileList] = useState([]) // 上传图片列表
  const [previewVisible, setPreviewVisible] = useState(false) // 图片是否可以预览
  const [previewImage, setPreviewImage] = useState(null) // 预览的图片

  // 根据id，获取文章详情
  useEffect(() => {
    if (!params.id) return
    async function getArticleInfoData () {
      const res = await getArticleInfo(params.id)

      // 给Form表单赋值
      formRef.current.setFieldsValue({
        ...res
      })

      // 设置图片类型 & 设置图片
      if (res.cover) {
        setCoverType(res.cover.type)

        const fileList = res.cover.images.map(image => {
          return {
            url: image,
            response: {
              data: {
                url: image
              }
            }
          }
        })
        setFileList(fileList)
      }
    }

    getArticleInfoData()
  }, [params.id])

  // 提交
  const publish = async () => {
    const values = await formRef.current
      .validateFields()
      .catch(err => console.log('err is---', err))

    if (!values) return

    // 图片类型和images数组
    values.cover = {}

    switch (coverType) {
      case 0:
        values.cover.type = 0
        values.cover.images = []
        break

      case 1:
        values.cover.type = 1
        values.cover.images = fileList.map(item => item.response.data.url)
        break

      case 3:
        values.cover.type = 3
        values.cover.images = fileList.map(item => item.response.data.url)
        break

      default:
        break
    }

    // 对cover做校验
    switch (values.cover.type) {
      case 1:
        if (fileList.length !== 1) {
          return
        }
        break

      case 3:
        if (fileList.length !== 3) {
          return
        }
        break

      default:
        break
    }

    // 发请求
    if (params.id) {
      // 修改文章
      values.id = params.id

      await dispatch(editArticle(values))
    } else {
      // 发布文章
      await dispatch(publishArticle(values))
    }

    // 跳转到文章列表页面
    navigate('/home/article')
  }

  const getBase64 = file => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => resolve(reader.result)
      reader.onerror = error => reject(error)
    })
  }

  // 预览图片
  const handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj)
    }

    setPreviewImage(file.url || file.preview)
    setPreviewVisible(true)
  }

  // 上传操作之前
  function beforeUpload (file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
      message.error('图片类型必须是 JPG/PNG!')
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('文件大小必须小于 2MB!')
    }

    return isJpgOrPng && isLt2M
  }

  // 上传之后
  const handleChange = ({ fileList }) => {
    setFileList(fileList)
  }

  // 获取提示文案
  const getHelp = () => {
    switch (coverType) {
      case 1:
        if (fileList.length !== 1) {
          return '请上传1张图片'
        } else {
          return null
        }

      case 3:
        if (fileList.length !== 3) {
          return '请上传3张图片'
        } else {
          return null
        }

      case 0:
        return null

      default:
        return null
    }
  }

  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to='/home'>首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>发布文章</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          name='basic'
          ref={formRef}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          initialValues={{ content: '' }}
          validateTrigger={['onChange', 'onBlur']}
        >
          <Form.Item
            label='标题'
            name='title'
            rules={[{ required: true, message: '请输入文章的标题' }]}
          >
            <Input style={{ width: 500 }} />
          </Form.Item>

          <Form.Item
            label='频道'
            name='channel_id'
            rules={[{ required: true, message: '请输入文章的标题' }]}
          >
            <Channel />
          </Form.Item>

          <Form.Item label='封面' validateStatus='error' help={getHelp()}>
            <Radio.Group
              onChange={e => {
                setCoverType(e.target.value)
                setFileList([])
              }}
              value={coverType}
            >
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item style={{ marginLeft: 190 }}>
            {coverType === 1 || coverType === 3 ? (
              <>
                {/* 一张图&三张图的处理 */}
                <Upload
                  name='image'
                  listType='picture-card'
                  className='avatar-uploader'
                  action={`${process.env.REACT_APP_URL}upload`}
                  fileList={fileList}
                  beforeUpload={beforeUpload}
                  onChange={handleChange}
                  onPreview={handlePreview}
                >
                  {fileList.length >= coverType ? null : <PlusOutlined />}
                </Upload>
                <Modal
                  visible={previewVisible}
                  footer={null}
                  onCancel={() => setPreviewVisible(false)}
                >
                  <img
                    alt='example'
                    style={{ width: '100%' }}
                    src={previewImage}
                  />
                </Modal>
              </>
            ) : (
              <></>
            )}
          </Form.Item>

          {/* 富文本 */}
          <Form.Item
            label='内容'
            name='content'
            rules={[
              {
                required: true,
                message: '请输入文章的内容'
              }
            ]}
          >
            <ReactQuill placeholder='请输入文章的内容' />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button type='primary' onClick={publish}>
                发布文章
              </Button>
              <Button type='info'>存入草稿</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Publish
